package com.file.service.impl;

import com.file.exceptions.ExceptionEnum;
import com.file.exceptions.ServiceException;
import com.file.form.result.ImgResultForm;
import com.file.service.IFileProcessService;
import com.file.utils.ConfigHelper;
import com.file.utils.Const;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;

/**
 * Created by chairal on 2017/7/21.
 */
@Service
public class FileProcessServiceImpl implements IFileProcessService {

    private final static Logger logger = LoggerFactory.getLogger(FileProcessServiceImpl.class);

    @Autowired
    ConfigHelper configHelper;

    /**
     * 上传图片到路径
     *
     * @param request
     */
    public ImgResultForm uploadFile(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String type = multipartRequest.getParameter("type");
        MultipartFile file = multipartRequest.getFile("file");
        if(file.isEmpty()){
            throw new ServiceException(ExceptionEnum.EMPTY_IMAGE);
        }
        //限制图片大小
        if (file.getSize() > 2 * 1024 * 1024) {
            throw new ServiceException(ExceptionEnum.IMAGE_LIMIT_ERROR);
        }
        try {
            //图片前缀路径
            String imgPrefixPath = configHelper.getImgPrefixPath();
            //日期
            String date = DateTime.now().toString("yyyyMMdd");
            //时间
            String time = DateTime.now().toString("yyyyMMddHHmmssSSS");
            //上传文件名
            String oldFileName = file.getOriginalFilename();
            //文件扩展名
            String extension = "";
            if (StringUtils.isNotEmpty(oldFileName) && oldFileName.indexOf('.') > -1) {
                extension = oldFileName.substring(oldFileName.lastIndexOf("."));
            }
            extension = extension.toLowerCase();
            //文件夹路径
            String saveFolderPath = "";
//            if("employee".equals(type)){
//                //文件夹路径
//                saveFolderPath = Const.SEPARATOR + type + Const.SEPARATOR + date;
//            }else if("org".equals(type)){
//                //文件夹路径
//                saveFolderPath = Const.SEPARATOR + type + Const.SEPARATOR + date;
//            }else if("orgType".equals(type)){
//                //文件夹路径
//                saveFolderPath = Const.SEPARATOR + type + Const.SEPARATOR + date;
//            }else{
//                //文件夹路径
//                saveFolderPath = Const.SEPARATOR + "other" + Const.SEPARATOR + date;
//            }
            saveFolderPath = Const.SEPARATOR + "contest" + Const.SEPARATOR + date;
            String folderPath = imgPrefixPath + saveFolderPath;
            File folder = new File(folderPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            //生成图片名
            String fileName = time + "_" + new Random().nextInt(1000) + extension;
            //数据库保存图片路径
            String savePath = saveFolderPath + Const.SEPARATOR + fileName;
            //生成图片路径
            String filePath = folderPath + Const.SEPARATOR + fileName;
            //输出图片
            File f = new File(filePath);
            FileOutputStream fos = new FileOutputStream(f);
            BufferedOutputStream out = new BufferedOutputStream(fos);
            out.write(file.getBytes());
            out.flush();
            out.close();
            //域名
            String domain = configHelper.getDomain();
            //图片映射路径
            String imgMapPath = configHelper.getImgMapPath();
            String imgUrl = domain + imgMapPath + savePath;
            ImgResultForm imgResultForm = new ImgResultForm();
            imgResultForm.setImgUrl(imgUrl);
            return imgResultForm;
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param request
     * @param response
     */
    public void downFile(HttpServletRequest request, HttpServletResponse response) {
        try {
            String imgUrl = request.getParameter("imgUrl");
            //构造URL
            URL url = new URL(imgUrl);
            //打开连接
            URLConnection con = url.openConnection();
            //设置请求超时为5s
            con.setConnectTimeout(15 * 1000);
            //输入流
            InputStream is = con.getInputStream();
            //图片名
            String fileName = "";
            File file = new File(imgUrl);
            fileName = file.getName();
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            //关闭流
            os.close();
            is.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 上传图片ftp服务器
     *
     * @param request
     */
    public ImgResultForm uploadFtpFile(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String type = multipartRequest.getParameter("type");
        MultipartFile file = multipartRequest.getFile("file");
        if (file.isEmpty()) {
            throw new ServiceException(ExceptionEnum.EMPTY_IMAGE);
        }
        try {
            //限制图片大小
            if (file.getSize() > 2 * 1024 * 1024) {
                throw new ServiceException(ExceptionEnum.IMAGE_LIMIT_ERROR);
            }
            //日期
            String date = DateTime.now().toString("yyyyMMdd");
            //时间
            String time = DateTime.now().toString("yyyyMMddHHmmssSSS");
            //上传文件名
            String oldFileName = file.getOriginalFilename();
            //文件扩展名
            String extension = "";
            if (StringUtils.isNotEmpty(oldFileName) && oldFileName.indexOf('.') > -1) {
                extension = oldFileName.substring(oldFileName.lastIndexOf("."));
            }
            extension = extension.toLowerCase();

            //图片前缀路径
            String ftpImgPrefixPath = configHelper.getFtpImgPrefixPath();
            //文件夹路径
            String saveFolderPath = Const.SEPARATOR + "contest" + Const.SEPARATOR + date;
            //文件夹全路径
            String folderPath = ftpImgPrefixPath + saveFolderPath;
            //生成图片名
            String fileName = time + "_" + new Random().nextInt(1000) + extension;

            /***************************ftp上传图片 start****************************/
            //ftp服务器ip
            String ftpServerIp = configHelper.getFtpServerIp();
            //ftp服务端口
            Integer ftpServerPort = configHelper.getFtpServerPort();
            //ftp服务器登录用户名
            String ftpServerUser = configHelper.getFtpServerUser();
            //ftp服务器登录密码
            String ftpServerPassword = configHelper.getFtpServerPassword();
            //FTPClient
            FTPClient ftpClient = new FTPClient();
            FileInputStream fis = null;
            try {
                //连接ftp服务器
                ftpClient.connect(ftpServerIp, ftpServerPort);
                //登录ftp服务器
                boolean loginStatus = ftpClient.login(ftpServerUser, ftpServerPassword);
                if (!loginStatus) {
                    throw new ServiceException(ExceptionEnum.FTP_LOGIN_ERROR);
                }
                //在ftp服务器创建文件夹，并切换工作目录
                String[] ftpFolder = folderPath.split("/");
                for(String folder : ftpFolder){
                    if(StringUtils.isNotEmpty(folder)){
                        //创建文件夹
                        ftpClient.makeDirectory(folder);
                        //切换工作目录
                        ftpClient.changeWorkingDirectory(folder);
                    }
                }
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");
                //设置文件类型（二进制）
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.storeFile(fileName, file.getInputStream());
                ftpClient.logout();
            } catch (IOException e) {
                throw new ServiceException(ExceptionEnum.FTP_CLIENT_ERROR);
            } finally {
                IOUtils.closeQuietly(fis);
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    throw new ServiceException(ExceptionEnum.FTP_CLOSE_EXCEPTION);
                }
            }
            /***************************ftp上传图片 end****************************/
            //ftp服务器图片映射路径
            String ftpImgMapPath = configHelper.getFtpImgMapPath();
            //图片路径
            String savePath = saveFolderPath + Const.SEPARATOR + fileName;
            //图片全路径
            String imgUrl = ftpImgMapPath + savePath;
            ImgResultForm imgResultForm = new ImgResultForm();
            imgResultForm.setImgUrl(imgUrl);
            return imgResultForm;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

}
